package com.hust.chatvedio;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.Volley;
import com.google.gson.Gson;
import com.hust.chatvedio.Entity.ChatMsgEntity;
import com.hust.chatvedio.adapter.ChatMsgViewAdapter;
import com.hust.chatvedio.utils.Utils;

import org.json.JSONArray;
import org.json.JSONException;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.app.PendingIntent.getActivity;

public class ChatActivity extends AppCompatActivity implements View.OnClickListener {
    private ImageButton mChatBack;
    private TextView mChatTitle;
    private ListView mListView1;
    private Button mChatSend;
    private List<ChatMsgEntity> mDataArrays = new ArrayList<>();
    private String message;//服务器返回值
    private int chatId;//服务器返回值
    private String far_user_name;//服务器返回值
    private Integer tempId = -1;//保留上一条信息
    private String sendContent;//发送的信息
    private String chatAvatar;
    private static final String TAG = "ChatActivity";
    //发送信息地址
    private static String url_sendmsg = MainActivity.BaseURL + "sendMsg";
    //获取历史对话
    private static String url_getChatLog = MainActivity.BaseURL + "getChatLog";
    //接收信息地址
    private static String url_getMsg = MainActivity.BaseURL + "getMsg";
    //getUserDetails
    private static String url_getUserDetails = MainActivity.BaseURL + "getUserDetails";
    private ChatMsgViewAdapter chatMsgViewAdapter;
    private EditText mEditText;
    private String chatName;
    private RequestQueue requestQueue;
    private Thread thread;
    private boolean isThreadRunning;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Utils.setStatusColor(this, false, true, R.color.colorPrimaryDarkMain2);
        setContentView(R.layout.activity_chat);
        //启动活动时不弹出软键盘
        getWindow().setSoftInputMode(
                WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN
        );
        initView();
        initData();
//        //声明一个线程，它将无限循环
        isThreadRunning = true;
        thread = new Thread(myRun);
        //开始异步执行
        thread.start();
    }

    @Override
    protected void onStop() {
        super.onStop();
        isThreadRunning = false;
        try {
            // Wait for the thread to finish
            thread.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    //聊天视图初始化
    private String[] msgArray = new String[]{"安卓很有前途哦"};

    private void initData() {
        Intent intent = getIntent();
        chatName = intent.getStringExtra("chatName");
        getUserDetails(chatName);
        mChatTitle.setText(chatName);
        getChatLog();
        chatMsgViewAdapter = new ChatMsgViewAdapter(mDataArrays, this);
        mListView1.setAdapter(chatMsgViewAdapter);
    }

    public void getUserDetails(String userName) {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        String url = url_getUserDetails + "?userName=" + userName;
        //在进行异步任务前先显示一个 Progress Dialog
        Request request = new JsonObjectRequest(0, url, (String) null,
                jsonObject -> {
                    try {
                        int success = jsonObject.getInt("success");
                        if (success == 1) chatAvatar = jsonObject.optString("data");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }, volleyError -> {
        });
        requestQueue.add(request);
    }

    private void initView() {
        mChatBack = (ImageButton) findViewById(R.id.chat_back);
        mChatTitle = (TextView) findViewById(R.id.chatTitle);
        mListView1 = (ListView) findViewById(R.id.listView1);
        mChatSend = (Button) findViewById(R.id.chat_send);
        mChatBack.setOnClickListener(this);
        mChatSend.setOnClickListener(this);
        mEditText = (EditText) findViewById(R.id.edit_text);
        mEditText.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.chat_back:
                finish();//返回上一页
                break;
            case R.id.chat_send:
                sendMsg();//发送信息
                break;
        }
    }

    private void getChatLog() {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        Map<String, String> map = new HashMap<>();
        map.put("userName", MainActivity.userName);
        map.put("name", chatName);
        Request request = new JsonObjectRequest(1, url_getChatLog, new Gson().toJson(map),
                jsonObject -> {
                    try {
                        chatId = jsonObject.getInt("success");
                        if (chatId == 1) {
                            mDataArrays.clear();
                            JSONArray data = jsonObject.getJSONArray("data");
                            int len = data.length();
                            for (int i = 0; i < len; i++) {
                                ChatMsgEntity entity = new ChatMsgEntity();

                                String userName = data.getJSONObject(i).optString("userName");
                                String chatContent = data.getJSONObject(i).optString("chatContent");
                                boolean isCome = userName.equals(MainActivity.userName) ? false : true;
                                entity.setName(userName);
                                entity.setComMeg(isCome);
                                entity.setText(chatContent);
                                entity.setAvatarUrl(isCome ? chatAvatar : MainActivity.userAvatar);
                                mDataArrays.add(entity);
                                if (i == len - 1) tempId = data.getJSONObject(i).optInt("chatId");
                            }
                            chatMsgViewAdapter.notifyDataSetChanged();
                            mEditText.setText("");
                            mListView1.setSelection(mListView1.getCount() - 1);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }, volleyError -> {
        });
        requestQueue.add(request);
    }

    private void sendMsg() {
        String contStrng = mEditText.getText().toString();
        if (contStrng.length() > 0) {
            sendContent = contStrng;
            ChatMsgEntity entity = new ChatMsgEntity();
            entity.setComMeg(false);
            entity.setText(contStrng);
            entity.setAvatarUrl(MainActivity.userAvatar);
            //本地显示

            Log.d(TAG, "sendMsg: " + MainActivity.userAvatar);
            mDataArrays.add(entity);
            chatMsgViewAdapter.notifyDataSetChanged();
            mEditText.setText("");
            mListView1.setSelection(mListView1.getCount() - 1);
            //发送到服务器
            sendToYun();
        }
    }

    private void sendToYun() {
        RequestQueue requestQueue = Volley.newRequestQueue(this);
        Map<String, String> map = new HashMap<>();
        map.put("sendContent", sendContent);
        map.put("userName", MainActivity.userName);
        map.put("receiverName", chatName);

        Request request = new JsonObjectRequest(1, url_sendmsg, new Gson().toJson(map),
                jsonObject -> {
                    try {
                        message = jsonObject.getString("message");
                        chatId = Integer.parseInt(jsonObject.optString("success"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }, volleyError -> {
        });
        requestQueue.add(request);
    }

    //一个异步线程
    Runnable myRun = () -> {
        while (isThreadRunning) {
            try {
                //放慢速度
                Thread.sleep(2500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //查询数据库
            getMsg();
            try {
                //放慢速度
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };

    private void getMsg() {
        if (requestQueue == null) requestQueue = Volley.newRequestQueue(this);
        String url = url_getMsg + "?userName=" + MainActivity.userName + "&chatName=" + chatName;
        Request request = new JsonObjectRequest(0, url, (String) null,
                jsonObject -> {
                    try {
                        message = jsonObject.optString("message");
                        chatId = jsonObject.getInt("success");
                        String avatar = jsonObject.optString("avatar");
                        if (chatId > tempId && message != null) {
                            String conString = message;
                            if (conString.length() > 0) {
                                ChatMsgEntity entity = new ChatMsgEntity();
                                entity.setAvatarUrl(avatar);
                                entity.setComMeg(true);
                                entity.setText(conString);
                                //本地显示
                                mDataArrays.add(entity);
                                chatMsgViewAdapter.notifyDataSetChanged();
                                mEditText.setText("");
                                mListView1.setSelection(mListView1.getCount() - 1);
                                Log.i("getMsgmData:", mDataArrays.toString());
                                tempId = chatId;
                            }
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }, volleyError -> {
        });
        requestQueue.add(request);
    }

}